package ua.kharkov.knure.pereverziev.diploma.web.command.admincommand;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import ua.kharkov.knure.pereverziev.diploma.db.DAOServices.ServiceFactory;
import ua.kharkov.knure.pereverziev.diploma.db.entity.Airport;
import ua.kharkov.knure.pereverziev.diploma.web.command.Command;
import ua.kharkov.knure.pereverziev.diploma.web.util.ConstantsUtility;

public class AddAirportCommand implements Command {

	private static final Logger log = Logger.getLogger(AddAirportCommand.class);

	@Override
	public String execute(final HttpServletRequest request,
			final HttpServletResponse response) throws IOException,
			ServletException {
		final HttpSession session = request.getSession();

		final String airport_city = request.getParameter("airport_city");
		log.trace("Request parameter: airport_sity --> " + airport_city);

		final String airport_name = request.getParameter("airport_name");

		log.trace("Request parameter: airport_name --> " + airport_name);

		// error handler
		// set forward to error page
		String forward = "/WEB-INF/jsp/error_page.jsp";
		final StringBuilder errorMessage = new StringBuilder();

		if (airport_city.isEmpty() || airport_name.isEmpty()) {
			errorMessage.append("One of the parameters is empty");
		} else {
			ServiceFactory.getInstance().getAirportService()
					.create(new Airport(airport_city, airport_name));

			ConstantsUtility.loadAirports(session.getServletContext());
			forward = "/WEB-INF/jsp/mainPage.jsp";
		}

		log.debug("Command finished");

		session.setAttribute("lastPage", forward);
		log.trace("Session attribute: lastPage --> " + forward);

		return forward;
	}
}
